import React, { useEffect, useState, useImperativeHandle, forwardRef } from 'react';
// import PropTypes from 'prop-types';
import _ from 'lodash';
import {
  Input,
  Button,
  Icon,
  Select,
  Tooltip,
  Popconfirm,
  Radio,
  InputNumber,
  message
} from 'antd';
import cn from 'classnames';
import ScanDrawer from '../../scan-drawer';
import { addscanRate, getscanRateList } from '@api/task';
// eslint-disable-next-line no-unused-vars
const ScanRate = (props, ref) => {
  // 扫描速率
  const [scanRate, setScanRate] = useState();
  // 最大连接并发配置
  const [connectionCountStatus, setConnectionCountStatus] = useState(1);
  // 最大连接数
  const [maxImumConnection, setMaxImumConnection] = useState(8);
  // 最大连接数错误提示
  const [connectionCountError, setConnectionCountError] = useState();
  // 连接数建议表
  const [drawerVisible, setDrawerVisible] = useState(false);
  // 扫描带宽
  const [scanBandwidth, setScanBandwidth] = useState(2000);
  // 扫描带宽报错
  const [scanBandwidthError, setScanBandwidthError] = useState('');
  // 扫描带宽选择按钮
  const [scanBandWidthStatus, setScanBandWidthStatus] = useState(1);
  const [templateName, setTemplateName] = useState();
  const [ScanRateTableList, setScanRateTableList] = useState([]);
  //获取端口列表
  const ScanRateList = id => {
    getscanRateList({ page: 1, pageSize: 200 }).then(res => {
      const data = res.data.data;
      _.get(data, 'list', []).push({
        name: '自定义',
        _id: 'custom',
        maximumConnection: 8,
        scanBandwidth: 2000
      });
      setScanRateTableList(_.get(data, 'list', []));
      // 新增后返回新增的那条数据
      if (id) {
        let item = _.get(data, 'list', []).filter(i => {
          return i._id === id;
        })[0]; // 默认为低
        setScanRate(item._id);
        setMaxImumConnection(item['maximumConnection'] ? item['maximumConnection'] : 0);
        setScanBandwidth(item['scanBandwidth'] ? item['scanBandwidth'] : 0);
        return;
      }
      if (_.get(data, 'list', []).length > 1) {
        let item = _.get(data, 'list', []).filter(i => {
          return i.name === '低';
        })[0]; // 默认为低
        setScanRate(item._id || 'custom');
        setMaxImumConnection(item['maximumConnection'] ? item['maximumConnection'] : 0);
        setScanBandwidth(item['scanBandwidth'] ? item['scanBandwidth'] : 0);
      } else {
        setScanRate('custom');
      }
    });
  };
  const findScanRate = type => {
    const scanRateItem = ScanRateTableList.find(r => r._id === scanRate);
    if (scanRateItem) {
      return scanRateItem[type];
    }
  };
  useEffect(() => {
    ScanRateList();
  }, []);
  useEffect(() => {
    if (connectionCountStatus === 0) {
      setMaxImumConnection(0);
    } else if (connectionCountStatus === 1) {
      setMaxImumConnection(8);
    }
  }, [connectionCountStatus]);
  useEffect(() => {
    if (scanBandWidthStatus === 0) {
      setScanBandwidth(0);
    } else if (scanBandWidthStatus === 1) {
      setScanBandwidth(2000);
    }
  }, [scanBandWidthStatus]);
  const popconfimInput = () => {
    return (
      <div>
        <Input
          value={templateName}
          onChange={e => setTemplateName(e.target.value)}
          placeholder="请输入模版名称"
        />
      </div>
    );
  };
  const renderConnectionCount = () => {
    const ChangeMaxImumConnection = value => {
      if (value < 1) {
        setConnectionCountError('配置参数不能小于1万');
        setMaxImumConnection(1);
      } else if (value > 500) {
        setConnectionCountError('配置参数不能大于500');
        setMaxImumConnection(500);
      } else {
        setConnectionCountError('');
      }
      setMaxImumConnection(value);
    };

    const ChangescanBandwidth = value => {
      let marker = false;
      if (value < 500) {
        setScanBandwidthError('扫描不能小于500万');
        marker = true;
      } else if (value > 50000) {
        setScanBandwidthError('配置参数不能大于50000');
        marker = true;
      } else {
        setScanBandwidthError('');
      }
      setScanBandwidth(marker ? 500 : value);
    };

    const submit = () => {
      if (!templateName) {
        message.error('请输入名称');
        return;
      }
      if (!~maxImumConnection) {
        message.error('请输入最大连接并发数');
        return;
      }
      if (!~scanBandwidth) {
        message.error('请输入扫描带宽');
        return;
      }

      const body = {
        name: templateName,
        maximumConnection: maxImumConnection,
        scanBandwidth
      };
      addscanRate(body)
        .then(data => {
          message.success('添加成功');
          setTemplateName('');
          ScanRateList(_.get(data, 'data.data._id'));
        })
        .catch(e => {
          message.error(e.message);
        });
    };
    return (
      <div style={{ marginLeft: 185, marginBottom: 30 }}>
        <div className={cn('item', 'connectionCount')}>
          <span className="item-title required f14">
            最大连接并发数
            <Tooltip
              title={
                '请根据上层转发设备所能建立的最大连接数或者目标资产的处理性能来合理设置。设置的越小，任务执行的时间越长。范围：1万-500万，默认值：8万'
              }
            >
              <Icon className={'icon-question'} type="exclamation-circle" />
            </Tooltip>
          </span>
          <Radio.Group
            value={connectionCountStatus}
            style={{ display: 'flex' }}
            onChange={e => {
              setConnectionCountStatus(e.target.value);
            }}
          >
            <Radio value={0}>不限制</Radio>
            <Radio value={1}>自定义</Radio>
          </Radio.Group>
          {connectionCountStatus === 1 && (
            <>
              <InputNumber
                value={maxImumConnection}
                onChange={ChangeMaxImumConnection}
                min={1}
                max={500}
                style={{ minWidth: 120 }}
              />
              <span className="unit">&nbsp;万</span>
              &nbsp;
            </>
          )}
        </div>
        {connectionCountError && (
          <p className={'validate-error connection-error'}>{connectionCountError}</p>
        )}
        <div className={cn('item', 'speed-limit')}>
          <span className="item-title f14 required">
            扫描带宽
            <Tooltip title="实际扫描所产生流量会因探测目标和端口的数量而不同，您可在这里设置最大允许的扫描带宽。最大为50000Kbps">
              <Icon type="exclamation-circle" />
            </Tooltip>
          </span>
          <Radio.Group
            onChange={e => {
              setScanBandWidthStatus(e.target.value);
            }}
            value={scanBandWidthStatus}
          >
            <Radio value={0}>不限制</Radio>
            <Radio value={1}>自定义</Radio>
          </Radio.Group>
          {scanBandWidthStatus === 1 && (
            <span className="speed-limit-input">
              <InputNumber
                min={500}
                max={50000}
                value={scanBandwidth}
                style={{ width: 120 }}
                onChange={ChangescanBandwidth}
              />
              <span className="unit">&nbsp;Kbps</span>
            </span>
          )}
        </div>
        {scanBandwidthError && (
          <p className={'validate-error connection-error'}>{scanBandwidthError}</p>
        )}
        {scanRate === 'custom' && (
          <>
            <Popconfirm
              placement="top"
              title={popconfimInput()}
              icon={' '}
              overlayClassName="Popconfirm"
              onConfirm={submit}
              okText="保存"
              cancelText="取消"
            >
              <Button type="primary" size={'small'} className=" mr-b-10">
                保存为策略模版
              </Button>
            </Popconfirm>
            <Tooltip title="可将输入的参数保存为策略模板，方便下次下发任务时选用，如无需保存为模板，则输入的参数将作为本次任务下发">
              <Icon type="exclamation-circle" style={{ marginLeft: 5 }} />
            </Tooltip>
          </>
        )}
      </div>
    );
  };

  const renderConnectionTips = () => {
    let Connection = findScanRate('maximumConnection');
    let Bandwidth = findScanRate('scanBandwidth');
    return (
      <p className="scan-rate-msg">
        最大连接并发数:{Connection === 0 ? '不限制' : Connection + '万'} 扫描带宽:
        {Bandwidth === 0 ? '不限制' : Bandwidth + 'Kbps'}
      </p>
    );
  };

  useImperativeHandle(ref, () => ({
    data: {
      erro: {
        connectionCountError,
        scanBandwidthError
      },
      maxImumConnection,
      scanBandwidth,
      templateName
    }
  }));
  return (
    <>
      <div className={'item'}>
        <span className="item-title">扫描速率</span>
        <Select
          onChange={e => {
            setScanRate(e);
            let item = ScanRateTableList.find(r => r._id === e);
            setMaxImumConnection(item['maximumConnection'] ? item['maximumConnection'] : 0);
            setScanBandwidth(item['scanBandwidth'] ? item['scanBandwidth'] : 0);
          }}
          defaultValue={''}
          getPopupContainer={triggerNode => triggerNode.parentNode}
          value={scanRate}
          style={{ width: '400px' }}
        >
          {ScanRateTableList.map(item => (
            <Select.Option value={item._id} key={item._id}>
              {item.name}
            </Select.Option>
          ))}
        </Select>
        <Button
          type="link"
          size="small"
          onClick={() => {
            setDrawerVisible(true);
          }}
          className={'icon-exclamation'}
        >
          连接数建议表
        </Button>
      </div>
      <ScanDrawer
        drawerVisible={drawerVisible}
        closeDrawer={() => {
          setDrawerVisible(false);
        }}
      />
      {scanRate === 'custom' && renderConnectionCount()}
      {scanRate !== 'custom' && renderConnectionTips()}
    </>
  );
};
export default forwardRef(ScanRate);
